import {Table, Icon, Button, Spin, Row, Col} from 'antd';
// import Table from '../../_antd1.11.2/table'
// import Icon from '../../_antd1.11.2/icon'
// import Button from '../../_antd1.11.2/button'
// import Spin from '../../_antd1.11.2/spin'
// import Row from '../../_antd1.11.2/row'
// import Col from '../../_antd1.11.2/col'

import WeaTools from '../wea-tools'
import WeaInput from '../wea-input'
import WeaSelect from '../wea-select'
import WeaBrowser from '../wea-browser'
import classNames from 'classnames'
import WeaCheckbox from '../wea-checkbox'
import isEqual from 'lodash/isEqual';


//国际化 zxt- 20170419
const defaultLocale = {
	total: '共',
	totalUnit: '条',
};

class Main extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
		antLocale: React.PropTypes.object,
	}
	getLocale() {
		let locale = {};
		if(this.context.antLocale && this.context.antLocale.Table) {
			locale = this.context.antLocale.WeaTableEdit;
		}
		return {
			...defaultLocale,
			...locale,
			...this.props.locale
		};
	}
	constructor(props) {
		super(props);
		this.state = {
			columns: [],
			datas: [],
			selectedRowKeys: [],
			current: 1
		}
		this.onEdit = this.onEdit.bind(this);
		this.doCopy = this.doCopy.bind(this);
		this.doDelete = this.doDelete.bind(this);
		this.doAdd = this.doAdd.bind(this);
	}
	componentDidMount() {
		const { datas = [], columns = [] } = this.props;
		columns.length > 0 && this.setState(datas.length > 0 ? {datas: this.addKeytoDatas(datas),columns} : {columns})
	}
	componentWillReceiveProps(nextProps) {
		const { columns = [], datas = [], selectedRowKeys = [] } = this.props;
		const _columns = nextProps.columns || [];
		const _datas = nextProps.datas || [];
		const _selectedRowKeys = nextProps.selectedRowKeys || [];
		!isEqual(columns,_columns) && this.setState({columns: _columns});
		!isEqual(datas,_datas) && this.setState({datas: this.addKeytoDatas(_datas)});
		!isEqual(selectedRowKeys,_selectedRowKeys) && this.setState({selectedRowKeys: _selectedRowKeys});
	}
	componentDidUpdate() {

	}
	addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
	render() {
		const { datas } = this.state;
		//rc-table 的底层 title 有问题，直接这里搞个吧
		return(
			<div className="wea-table-edit" >
				{this.getTitle()}
                <Table
                	columns={this.getColumns()}
                	dataSource={datas}
                	pagination={this.getPagination()}
                	rowSelection={this.getRowSelection()}
                />
            </div>
		)
	}
	getTitle(){
		const { title = '',viewAttr = 2 } = this.props;
		const { columns, selectedRowKeys } = this.state;
		let readOnly = viewAttr === 1
		return (
			<Row className="wea-table-edit-title" >
				<Col>
					{ title }
					<Button style={{display:readOnly?'none':'block'}} type="primary" disabled={readOnly ||!`${selectedRowKeys}`} title='复制' size="small" onClick={this.doCopy} ><Icon type="copy" /></Button>
					<Button style={{display:readOnly?'none':'block'}} type="primary" disabled={readOnly ||!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete} ><Icon type="minus" /></Button>
					<Button style={{display:readOnly?'none':'block'}} type="primary" disabled={readOnly ||!`${columns}`} title='新增' size="small" onClick={this.doAdd}><Icon type="plus" /></Button>
				</Col>
            </Row>
		)
	}
	getColumns(){
		const { columns } = this.state;
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			_col.render || (_col.render = ( text, record, index ) => {
				return this.getColRender( _col, text, record, index );
			})
			return _col
		});
		return _columns
	}
	getColRender( _col, text, record, index ){
		const { com } = _col;
		let _com = [];
		com.map(c => {
			if(typeof c.props === 'object'){
				_com.push(c);
			}else{
				const { key, label = '', type = 'INPUT', options = [], browserConditionParam = {}, width = 120, viewAttr = 2 } = c;
				const _type = type.toUpperCase();
				_com.push(
					<span >
						{label && <span style={{marginLeft: 5}}>{label}</span>}
						{ _type === 'INPUT' &&
							<WeaInput
								defaultValue={record[key]}
								value={record[key]}
								style={{width, display: 'inline-block'}}
								viewAttr={ viewAttr }
								onBlur={value => this.onEdit(record, index, key, value)} />
						}
						{ _type === 'SELECT' &&
							<WeaSelect
								defaultValue={record[key]}
								value={record[key]}
								options={options}
								style={{width, display: 'inline-block'}}
								viewAttr={ viewAttr }
								onChange={value => this.onEdit(record, index, key, value)} />
						}
						{ _type === 'BROWSER' &&
							<WeaBrowser
								replaceDatas={this.getBrowerDatas(record, key)}
								{...browserConditionParam}
								inputStyle={{width, display: 'inline-block'}}
								viewAttr={ viewAttr }
								onChange={(ids, names, bDatas) => this.onEdit(record, index, key, ids, names, bDatas)} />
						}
						{ _type === 'CHECKBOX' &&
							<WeaCheckbox
			                    style={{width, display: 'inline-block'}}
			                    value={record[key]}
			                    viewAttr={ viewAttr }
			                    onChange={(value) => this.onEdit(record, index, key, value)}
			                />
						}
					</span>
				)
			}
		});
		return (
			<div>
				{_com}
			</div>
		)
	}
	getBrowerDatas(record, key){
		let replaceDatas = [];
		if(record[key + 'span'] !== undefined) {
			let keys = record[key].split(',');
			let values = record[key + 'span'].split(',');
			if(keys.length === values.length){
				keys.map((k, i) => {
					if (k != '' && values[i] != '') replaceDatas.push({id: k, name: values[i]});
				});
			}else{
				console.log('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "');
			}
		}
		return replaceDatas
	}
	getPagination() {
		const { pageSize = 0, paginationSize = ''} = this.props;
		if( !pageSize ) return false;
		const { current } = this.state;
		const locale = this.getLocale();
		let obj = {
			size: paginationSize,
			current,
			pageSize,
		};
		return obj
	}
	getRowSelection(){
		const { columns, selectedRowKeys } = this.state;
		if(!`${columns}`) return null
		const rowSelection = {
			selectedRowKeys,
			onChange: (sRowKeys, selectedRows) => {
				//console.log('selectedRowKeys: ',sRowKeys);
				this.setState({selectedRowKeys : sRowKeys});
				typeof this.props.onRowSelect === 'function' && this.props.onRowSelect(sRowKeys);
			}
		}
		return rowSelection
	}
	onEdit(record, index, key, value, names, bDatas){
		// console.log('onEdit: ',record, index, key, value, names, bDatas);
		const { pageSize = 0 } = this.props;
		const { datas, current } = this.state;
		let _datas = [].concat(datas);
		_datas[pageSize * (current - 1) + index][key] = value;
		if(names) _datas[pageSize * (current - 1) + index][key + 'span'] = names;
		this.setState({datas: _datas});
		this.onChange(_datas);
	}
	doCopy(){
		const { datas, current, selectedRowKeys } = this.state;
		let _datas = [].concat(datas);
		selectedRowKeys.map(key => {
			datas.map(data => {
				if(data.key == key){
					let _data = {...data};
					_data.key = _datas.length;
					_datas.push(_data)
				}
			})
		});
		this.setState({datas: _datas});
		this.onChange(_datas);
	}
	doAdd(){

		const { datas, current, selectedRowKeys } = this.state;
		let _datas = [].concat(datas);
		let _data = {...datas[0]};
		for(let k in _data){
			_data[k] = ''
		}
		_data.key = _datas.length;
		_datas.push(_data);
		this.setState({datas: _datas});
		this.onChange(_datas);
	}
	doDelete(){
		const { datas, current, selectedRowKeys } = this.state;
		let _datas = [].concat(datas);
		selectedRowKeys.map(key => {
			_datas = _datas.filter(data => data.key !== key)
		});
		_datas = _datas.map((data, i) => {
			let _data = {...data};
			_data.key = i;
			return _data
		})
		this.setState({datas: _datas,selectedRowKeys: []});
		this.onChange(_datas);

	}
	onChange(datas){
		const { columns } = this.state;
		//console.log('onChange datas: ', datas);
		let _datas = datas.map((data, i) => {
			let _data = {...data}
			delete _data.key
			return _data
		})
		//console.log('onChange _datas: ', _datas);
		typeof this.props.onChange === 'function' && this.props.onChange(_datas, columns);
	}
}

export default Main;

//let columns_mock = [
//	{
//		title: '测试 mock1',
//		dataIndex: 'mock1',
//		key: 'mock1',
//		com: [
//			<span>直接传入组件</span>
//		],
//		colSpan: 1,
//		width: '20%',
//		className: 'test-mock1',
//	},
//	{
//		title: '测试 mock2',
//		dataIndex: 'mock2',
//		key: 'mock2',
//		com: [
//			{ label: '', type: 'BROWSER' , editType: '1', key: 'browser', browserConditionParam: {}, width: 120, },
//		],
//		colSpan: 1,
//		width: '20%',
//		className: 'test-mock2',
//	},
//	{
//		title: '测试 mock',
//		dataIndex: 'mock',
//		key: 'mock',
//		com: [
//			{ label: '', type: 'SELECT' ,editType: '1', key: 'fieldtype', options: [{ key: '0', showname: '单行文本框'},{ key: '1', showname:'多行文本框'}], width: 120, disabled: false, },
//			{ label: '类型：', type: 'SELECT' ,editType: '1', key: 'type', options: [{ key: '0', showname: '文本'}], width: 120, },
//			{ label: '文本长度：', type: 'INPUT' ,editType: '1', key: 'fieldlength', width: 120, },
//		],
//		colSpan: 1,
//		width: '60%',
//		className: 'test-mock',
//	},
//];

//let datas_mock = [
//	{
//		key: 0,
//		fieldtype: '0',
//		type: '0',
//		fieldlength: 200,
//      browserspan:'w1'
//      browser:'3'
//	}
//];